<template>
  <a-cascader
    :options="categoryData"
    :field-names="fieldColum"
    :show-search="{ filter }"
    placeholder="请选择分类"
    v-model="values"
    @change="onChange"
  />
</template>
<script>

import { treeCategory } from '@/api/wms/base/category'

export default {
  name: 'CategorySelect',
  props: {
    categoryId: {
      type: String,
      default: undefined
    }
  },
  data () {
    return {
      values: [],
      categoryData: [],
      fieldColum: { label: 'categoryName', value: 'categoryId', children: 'children' }
    }
  },
  watch: {
    categoryId: function () {
      this.loadTree()
    }
  },
  methods: {
    loadTree () {
      treeCategory(this.queryParam).then(res => {
          if (res.code === 200) {
            this.categoryData = res.data
            this.values = []
            if (this.categoryId) {
              this.values = this.buildCategoryId(res.data, this.categoryId)
              this.values.reverse()
            }
          }
        }
      )
    },
    onChange (value, selectedOptions) {
      if (value) {
        const data = selectedOptions[selectedOptions.length - 1]
        this.$emit('selectedCategory', data)
      }
    },
    filter (inputValue, path) {
      return path.some(option => option.categoryName.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    buildCategoryId (data, val) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].categoryId === val) {
          return [data[i].categoryId]
        }
        if (data[i].children) {
          const array = this.buildCategoryId(data[i].children, val)
          if (array !== undefined) {
            return array.concat(data[i].categoryId)
          }
        }
      }
    }
  },
  created () {
    this.loadTree()
  }
}
</script>
